package com.springboot.cloud.demos.feign.rest;

import cn.jpush.api.push.model.PushPayload;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.jiguang.JpushUtil;
import com.springboot.cloud.common.core.util.RandomUtil;
import com.springboot.cloud.demos.entity.po.User;
import com.springboot.cloud.demos.feign.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class JpushController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private JpushUtil jpushUtil;

    /***
     * 发起语音/视频通话请求
     * @param  userId  受邀请的用户ID
     * @param  type  请求类型：video，视频，voice：语音（连麦）
     */
    @PostMapping("/jpush/call")
    public Result call(HttpServletRequest request, String userId, String type) {
        User user = getUser(request);
        String code = RandomUtil.getRandomNumString(5);
        Result<User> invitedUserResult = userService.getById(userId);
        if (invitedUserResult.isSuccess()) {
            User invitedUser = invitedUserResult.getData();
            String channelName = user.getId() + invitedUser.getId() + code;
            PushPayload payload = jpushUtil.buildVideoPayLoad(user.getNickname(), invitedUser.getRegistrationId(), type, "start",channelName,user.getId());
            jpushUtil.send(payload);
            return Result.success(channelName);
        }

        return Result.fail();
    }

    /***
     * 发起语音/视频通话请求
     * @param  userId  受邀请的用户ID
     * @param  type  请求类型：video，视频，voice：语音（连麦）
     */
    @PostMapping("/jpush/endCall")
    public Result endCall(HttpServletRequest request, String userId, String type,String chanelName) {
        User user = getUser(request);
        Result<User> invitedUserResult = userService.getById(userId);
        if (invitedUserResult.isSuccess()) {
            User invitedUser = invitedUserResult.getData();
            PushPayload payload = jpushUtil.buildVideoPayLoad(user.getNickname(), invitedUser.getRegistrationId(), type,"end", chanelName,user.getId());
            jpushUtil.send(payload);
        }

        return Result.success();
    }
}
